package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    // 订单
    @Autowired
    private OrderMapper orderMapper;
    // 订单明细
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    // 收货地址
    @Autowired
    private AddressMapper addressMapper;
    // 获取购物车注入service（之前已完成）
    @Autowired
    private CartService cartService;
    @Override
    public void submit(Order order) {
        //获取登录User对象
        User user = UserHolder.get();
        if (user == null) {
            throw new CustomException("用户未登录，不能下单");
        }
        //2.查询收货地址对象
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("收货地址为空，不能下单");
        }
        // 3.获取购物车List集合
        List<Cart> cartServiceList = cartService.findList();
        if (cartServiceList==null&&cartServiceList.size()==0) {
            throw new CustomException("收货地址为空，不能下单");
        }
        // 通过mp实现生成雪花id
        Long orderId = IdWorker.getId();
        //订单总金额
        BigDecimal orderAmount = new BigDecimal(0);
        // 4.遍历购物车集合封装订单明细
        for (Cart cart : cartServiceList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());// 菜品或套餐名称
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount()); // 单价
            orderDetail.setImage(cart.getImage());// 图片
            // 调用mapper保存
            orderDetailMapper.insert(orderDetail);
            // 累加订单金额
            // orderAmount = orderAmount+(cart.getAmount()*cart.getNumber())
            orderAmount = orderAmount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        // 5.封装订单
        order.setId(orderId); // 订单id
        order.setNumber(orderId.toString()); // 订单号
        order.setStatus(1);// 待付款
        order.setUserId(user.getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(orderAmount);
        order.setUserName(user.getName());
        order.setPhone(user.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        // 6.保存订单
        orderMapper.insert(order);
        // 7.清空购物车
        cartService.clean();
    }

    @Override
    public Page<Order> findByPage(Integer page, Integer pageSize) {
        //根据userid查询出当前账户的订单
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        qw.eq(Order::getUserId, UserHolder.get().getId());
        //查询分页
        Page<Order> orderPage = new Page<>(page, pageSize);
        orderMapper.selectPage(orderPage, qw);
        //根据每个对象的id查询出每个订单中的菜品
        List<Order> orderList =orderPage.getRecords();
        for (Order order : orderList) {
            //设置条件
            LambdaQueryWrapper<OrderDetail> dqw = new LambdaQueryWrapper<>();
            dqw.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(dqw);
            //存入数据
            order.setOrderDetails(orderDetails);
            /*order.setOrderDetails(orderDetails);*/
        }
        return orderPage;


    }

    @Override
    public Page<Order> findByDdPage(Integer page, Integer pageSize, Long number, Date beginTime, Date endTime) {
        LambdaQueryWrapper<Order> qw = new LambdaQueryWrapper<>();
        //先判断number是否为空
        if (number != null) {
        qw.like( Order::getNumber, number);
        }
        //判断时间在区间
        if (beginTime != null) {
        qw.gt(Order::getOrderTime, beginTime);
        }
        if (endTime != null) {
        qw.lt( Order::getOrderTime, endTime);
        }
        Page<Order> orderPage = new Page<>(page, pageSize);
        orderPage = orderMapper.selectPage(orderPage, qw);
        return orderPage;

    }
}
